package com.itheima.utils;

import com.itheima.pojo.Menu;

import java.util.ArrayList;
import java.util.List;

public class MenuUtil {
    public static List<Menu> getMenuList(List<Menu> entityList) {
        List<Menu> resultList = new ArrayList<>();
        //获取顶层元素集合
        Integer parentCode;
        for (Menu entity : entityList) {
            parentCode = entity.getParentMenuId();
            //parentCode==null代表一级菜单
            if (parentCode == null ) {
                resultList.add(entity);
            }
        }
        //获取每个一级菜单的子数据集合
        for (Menu entity : resultList) {
            entity.setChildren(getSubList(entity.getId(), entityList));
        }
        return resultList;
    }
    private static List<Menu> getSubList(Integer id, List<Menu> entityList) {
        List<Menu> childList = new ArrayList<>();
        Integer parentId;
        //子集的直接子对象
        for (Menu entity : entityList) {
            parentId = entity.getParentMenuId();
            if (id.equals(parentId)) {
                childList.add(entity);
            }
        }
        //子集的间接子对象
        for (Menu entity : childList) {
            entity.setChildren(getSubList(entity.getId(), entityList));
        }
        //递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}